package com.dayu.recovery.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.dayu.basic.domain.BasicSupplier;
import com.dayu.basic.domain.BasicTestValues;
import com.dayu.basic.mapper.BasicSupplierMapper;
import com.dayu.basic.service.IBasicTestValuesService;
import com.dayu.common.core.domain.entity.SysUser;
import com.dayu.common.utils.SecurityUtils;
import com.dayu.common.utils.StringUtils;
import com.dayu.recovery.domain.*;
import com.dayu.recovery.domain.bo.GoodsQueryBo;
import com.dayu.recovery.domain.constant.GoodsConstant;
import com.dayu.recovery.mapper.*;
import com.dayu.recovery.service.IRecoveryModifyService;
import com.dayu.store.domain.StoreCollect;
import com.dayu.store.mapper.StoreCollectMapper;
import com.dayu.store.service.IStoreCollectService;
import com.dayu.system.service.ISysUserService;
import com.dayu.utils.BarCodeUtils;
import com.dayu.utils.RandomOrderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dayu.recovery.service.IRecoveryGoodsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * 回收商品管理Service业务层处理
 *
 * @author HK
 * @date 2021-04-16
 */
@Service
public class RecoveryGoodsServiceImpl implements IRecoveryGoodsService
{
    @Resource
    private RecoveryGoodsMapper recoveryGoodsMapper;
    @Resource
    private StoreCollectMapper storeCollectMapper;
    @Resource
    private IBasicTestValuesService testValuesService;
    @Resource
    private IRecoveryModifyService modifyService;

    @Resource
    private RecoveryGoodsRecordMapper goodsRecordMapper;

    @Resource
    private IStoreCollectService storeCollectService;

    @Resource
    private RecoveryLoanMapper recoveryLoanMapper;

    @Resource
    private RecoveryStockMapper stockMapper;

    @Resource
    private BasicSupplierMapper basicSupplierMapper;

    @Resource
    private RecoveryCollectMapper collectMapper;

    /**
     * 查询回收商品管理
     *
     * @param goodsId 回收商品管理ID
     * @return 回收商品管理
     */
    @Override
    public RecoveryGoods selectRecoveryGoodsById(String goodsId)
    {
        RecoveryGoods goods = recoveryGoodsMapper.selectRecoveryGoodsById(goodsId);
        if(ObjectUtils.isEmpty(goods))
            throw new RuntimeException("未查询到数据，请输入正确的商品编码");
        if(!ObjectUtils.isEmpty(goods.getStoreId())){
            StoreCollect collect = storeCollectService.selectStoreCollectById(goods.getStoreId());
            goods.setStoreCollect(collect);
        }
        return goods;
    }

    @Override
    public RecoveryGoods queryGoodsNormalById(String goodsId) {
        RecoveryGoods goods = recoveryGoodsMapper.selectRecoveryGoodsBySn(goodsId);
        if(ObjectUtils.isEmpty(goods)) {
            goods = selectRecoveryGoodsById(goodsId);
        }
        if(goods.getGoodsStatus() != GoodsConstant.GOODS_STATUS_OK)
            throw new RuntimeException("商品状态不正常，不可操作!");

        //获取供应商
        if(!ObjectUtils.isEmpty(goods.getCollectId())) {
            RecoveryCollect collect = collectMapper.selectRecoveryCollectById(goods.getCollectId());
            if(!ObjectUtils.isEmpty(collect)) {
                BasicSupplier supplier = basicSupplierMapper.selectBasicSupplierById(collect.getSourceId());
                if(!ObjectUtils.isEmpty(supplier))
                    goods.setSupplierName(supplier.getSupplierName());
            }
        }else {
            goods.setSupplierName("散户");
        }

        goods.setTestName(recoveryGoodsMapper.queryTestName(goodsId));
        return goods;
    }

    public List<RecoveryGoodsRecord> queryRecordList(RecoveryGoodsRecord bo)  {
        return goodsRecordMapper.selectRecoveryGoodsRecordList(bo);
    }

    /**
     * 查询回收商品管理列表
     *
     * @param recoveryGoods 回收商品管理
     * @return 回收商品管理
     */
    @Override
    public List<RecoveryGoods> selectRecoveryGoodsList(RecoveryGoods recoveryGoods)
    {
        if(recoveryGoods.getParams() != null) {
            String str = (String) recoveryGoods.getParams().get("goodsIds");
            if(str != null) {
                recoveryGoods.getParams().put("goodsIds", str.split(","));
            }
        }

        return recoveryGoodsMapper.selectRecoveryGoodsList(recoveryGoods);
    }

    @Override
    public List<Map<String, Object>> queryFinenessChatData() {
        return recoveryGoodsMapper.queryFinenessChatData();
    }

    @Override
    public List<Map<String, Object>> queryBrandChatData() {
        return recoveryGoodsMapper.queryBrandChatData();
    }

    @Override
    public Map<String, Object> querySaleAndCostChatData(GoodsQueryBo bo) {
        if(ObjectUtils.isEmpty(bo.getTime()))
            bo.setTime("day");

        List<Map<String, Object>> list;
        if(Objects.equals(bo.getTime(), "year") || Objects.equals(bo.getTime(), "month")){
            list = recoveryGoodsMapper.querySaleAndCostChatDataByTime(bo);
        }
        else {
            list = recoveryGoodsMapper.querySaleAndCostChatData();
        }
        List<Object> date = new ArrayList<>();
        List<Object> cost = new ArrayList<>();
        List<Object> sale = new ArrayList<>();

        list.forEach(item -> {
            date.add(item.get("date"));
            Object c = ObjectUtils.isEmpty(item.get("cost")) ? 0 :  item.get("cost");
            Object s = ObjectUtils.isEmpty(item.get("sale")) ? 0 :  item.get("sale");
            cost.add(c);
            sale.add(s);
        });
        Map<String, Object> res = new HashMap<>();
        res.put("date", date);
        res.put("cost", cost);
        res.put("sale", sale);
        return res;
    }

    public List<Map<String, Object>> queryIndexData(GoodsQueryBo bo){
        if(ObjectUtils.isEmpty(bo.getTime()))
            bo.setTime("day");
        return recoveryGoodsMapper.queryIndexData(bo);
    }

    @Override
    public List<Map<String, Object>> queryChatDataByCostPrice() {
        RecoveryGoods goods = new RecoveryGoods();
        List<RecoveryGoods> list = recoveryGoodsMapper.selectRecoveryGoodsList(goods);
        Integer k1 = 0; //1000以下
        Integer k2 = 0; //1000-1999
        Integer k3 = 0; //2000-2999
        Integer k4 = 0; //3000-4999
        Integer k5 = 0; //5000以上

        for (RecoveryGoods item : list) {
            if(ObjectUtils.isEmpty(item.getCostPrice()))
                continue;
            double a = item.getCostPrice().doubleValue();
            if(a < 1000)
                k1++;
            else if(a < 2000)
                k2++;
            else if(a < 3000)
                k3++;
            else if(a < 4000)
                k4++;
            else
                k5++;
        }

        List<Map<String, Object>> res = new ArrayList<>();
        res.add(createChatMap("1000以下", k1));
        res.add(createChatMap("1000-1999", k2));
        res.add(createChatMap("2000-2999", k3));
        res.add(createChatMap("3000-4999", k4));
        res.add(createChatMap("5000以上", k5));

        return res;
    }

    private Map<String, Object> createChatMap(String name, Object value) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("value", value);
        return map;
    }

    /**
     * 数据导出
     * @param recoveryGoods 回收商品管理
     * @param bool
     * @return
     */
    @Override
    public List<RecoveryGoods> exportRecoveryGoodsList(RecoveryGoods recoveryGoods, boolean bool) {
        System.out.println("当前权限： " + bool);
        List<RecoveryGoods> list = selectRecoveryGoodsList(recoveryGoods);
        //所有调价数据
        List<RecoveryModify> modifyList = modifyService.selectRecoveryModifyList(new RecoveryModify());
        RecoveryLoan queryLoan = new RecoveryLoan();
        queryLoan.setStatus(1);
        List<RecoveryLoan> loanList = recoveryLoanMapper.selectRecoveryLoanList(queryLoan);
        //仓库
        List<RecoveryStock> stockList = stockMapper.selectRecoveryStockList(new RecoveryStock());
        for(RecoveryGoods goods : list) {
            System.out.println("供应商1：" + goods.getSupplierName());
            if(!bool) {
                goods.setSupplierName("");
            }
            System.out.println("供应商2：" + goods.getSupplierName());
            //获取暂借人
            for (RecoveryLoan loan : loanList) {
                if(loan.getGoodsId().equals(goods.getGoodsId())) {
                    goods.setLoanName(loan.getLoanName());
                    break;
                }
            }
            for(RecoveryStock stock : stockList) {
                if(stock.getStockId().equals(goods.getStockId())) {
                    goods.setStockName(stock.getStockName());
                }
            }
            //获取调价列表，并生成新的列表
            modifyList = goods.builderModifyList(modifyList);
        }
        return list;
    }

    /**
     * 修改回收商品管理
     *
     * @param bo 回收商品管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRecoveryGoods(RecoveryGoods bo)
    {
        RecoveryGoodsRecord goodsRecord = new RecoveryGoodsRecord();
        goodsRecord.setGoodsId(bo.getGoodsId());
        goodsRecord.setGoodsName(bo.getGoodsName());
        goodsRecord.setGoodsSn(bo.getGoodsSn());
        goodsRecord.setSpecs(bo.getPrinting());
        goodsRecord.setTestInfo(bo.getTestInfo());
        goodsRecord.setCostPrice(bo.getCostPrice());
        goodsRecord.setCreateName(SecurityUtils.getLoginUser().getUser().getNickName());
        goodsRecord.setCreateBy(SecurityUtils.getUsername());
        goodsRecord.setCreateTime(new Date());
        goodsRecord.setRemark(bo.getRemark());
        goodsRecord.setType(ObjectUtils.isEmpty(bo.getUpdateStatus()) ? 0 : bo.getUpdateStatus());
        if(ObjectUtils.isEmpty(bo.getRecordId())) {
            goodsRecordMapper.insertRecoveryGoodsRecord(goodsRecord);
        }else {
            goodsRecord.setId(bo.getRecordId());
            goodsRecord.setUpdateTime(new Date());
            goodsRecordMapper.updateGoodsRecord(goodsRecord);
        }
        return recoveryGoodsMapper.updateRecoveryGoods(bo);
    }

    @Override
    public RecoveryGoodsRecord addGoodsRecord(RecoveryGoodsRecord record) {
        if(record.getGoodsId() == null)
            return new RecoveryGoodsRecord();
        //查询是否有未完成的日志
        RecoveryGoodsRecord sel = new RecoveryGoodsRecord();
        sel.setGoodsId(record.getGoodsId());
        if(ObjectUtils.isEmpty(record.getType())) {
            sel.setType(0);
        }else {
            sel.setType(record.getType());
        }
        sel.setCreateBy(SecurityUtils.getUsername());
        RecoveryGoodsRecord old = goodsRecordMapper.queryNotUpdate(sel);
        if(!ObjectUtils.isEmpty(old) && !ObjectUtils.isEmpty(old.getId()))
            return old;
        record.setCreateName(SecurityUtils.getLoginUser().getUser().getNickName());
        record.setCreateBy(SecurityUtils.getUsername());
        record.setCreateTime(new Date());
        goodsRecordMapper.insertRecoveryGoodsRecord(record);
        return record;
    }

    /**
     * 批量删除回收商品管理
     *
     * @param goodsIds 需要删除的回收商品管理ID
     * @return 结果
     */
    @Override
    public int deleteRecoveryGoodsByIds(String[] goodsIds)
    {
        return recoveryGoodsMapper.deleteRecoveryGoodsByIds(goodsIds);
    }

    /**
     * 根据回收数据批量生成
     * @param collect
     * @return
     */
    @Override
    @Transactional
    public int insertRecoveryGoodsByList(RecoveryCollect collect) {
        Integer num = collect.getCollectNum();
        if("y".equals(collect.getHasGreen())) {
            num = 1;
        }
        //生成随机回收单号组
        Set<String> orderNums = RandomOrderUtils.randomOrderNumSet(num);
        List<RecoveryGoods> goodsList = new ArrayList<>();
        ///价格组
        String[] arr = StringUtils.isNotEmpty(collect.getCollectPrice()) ? collect.getCollectPrice().split(",") : null;
        Date date = new Date();
        int i = 0;
        for(String order : orderNums) {
            RecoveryGoods goods = new RecoveryGoods();
            goods.setGoodsId(order);
            if("y".equals(collect.getHasGreen())) {
                goods.setGoodsName("绿色回收");
                goods.setGoodsSn("绿色回收 回收编号" + collect.getCollectId());
                goods.setPrinting("数量: " + collect.getCollectNum());
            }

            if(arr != null && i < arr.length) {
                goods.setCostPrice(new BigDecimal(arr[i]));
                i++;
            }
            goods.setBarCode(BarCodeUtils.getBarCodeUrl(order));
            goods.setCollectId(collect.getCollectId());
            goods.setCreateTime(date);
            goodsList.add(goods);
        }

        //根据门店回收单号，生成数据(设置参数)
        if(collect.getStoreIds() != null) {
            List<StoreCollect> storeList = storeCollectMapper.selectStoreCollectByIds(collect.getStoreIdsInLong());
            for(int j = 0; j < storeList.size(); j++) {
                RecoveryGoods goods = goodsList.get(j);
                StoreCollect storeCollect = storeList.get(j);
                goods.setStoreId(storeCollect.getStoreId()); //门店id
                goods.setShareGoodsId(storeCollect.getModelId()); //型号
                //合计
                storeCollect.setTotalPrice(new BigDecimal(0));
                goods.setCostPrice(storeCollect.getTotalPrice()); //合计
                goods.setGoodsSn(storeCollect.getModelSn()); //串号
            }
        }
        return recoveryGoodsMapper.insertRecoveryGoodsByList(goodsList);
    }

    /**
     * 查询某个仓库 成本和
     * @param recoveryGoods 仓库id
     * @return 成本和
     */
    @Override
    public Map<String, Object> selectStockGoodsPrice(RecoveryGoods recoveryGoods) {
        return recoveryGoodsMapper.selectStockGoodsPrice(recoveryGoods);
    }
}
